import time from 'locutus/php/datetime/time';

const {action} = jinghuan.props;

class fitting extends jinghuan.AdminController {

    @action({})
    async datatable(get, {page, length}) {
        let model_ = this.db('jh_fitting').where('status', 1).limit(length).offset((page - 1) * length);
        let model  = this.db().from(model_.as('a')).leftJoin('jh_carscategory as b','b.id','a.serie_id').leftJoin('jh_fitting_type as c','c.id','a.type_id').select('a.*','b.name as serie','c.name as type');
        let model2 = this.db('jh_fitting').where('status', 1).count('id as count');
        await this.default_datatable2(model, model2);
    }

    @action({})
    async do_add(get, post) {
        try {
            post.time = post.u_time = time();
            post.shop_id = post.user_id = 0;

            let res = await this.db('jh_fitting').insert(post);

            let row_ = this.db('jh_fitting').where('id', res[0]).first();
            let row  = await this.db().from(row_.as('a')).leftJoin('jh_carscategory as b','b.id','a.serie_id').leftJoin('jh_fitting_type as c','c.id','a.type_id').first('a.*','b.name as serie','c.name as type');
            this.callback(row,{toast:'message.success.add'});
        } catch (e) {
            if (e.errno == 1062) {
                this.callback(false,{toast:'message.error.code'});
            } else {
                this.callback(false,{toast:'message.error.add'});
            }
        }
    }

    @action({})
    async do_edit(get, post) {
        try {
            post.u_time = time();
            post.user_id = 0;

            let res = await this.db('jh_fitting').where('id', post.id).update(post);

            let row_ = this.db('jh_fitting').where('id', post.id).first();
            let row  = await this.db().from(row_.as('a')).leftJoin('jh_carscategory as b','b.id','a.serie_id').leftJoin('jh_fitting_type as c','c.id','a.type_id').first('a.*','b.name as serie','c.name as type');
            this.callback(row,{toast:'message.success.edit'});
        } catch (e) {
            if (e.errno == 1062) {
                this.callback(false,{toast:'message.error.code'});
            } else {
                this.callback(false,{toast:'message.error.edit'});
            }
        }


    }
}

export default fitting;